

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;

import net.sf.json.JSONObject;



public class HttpUtil {
	private static final String LOGPRE = "各省石油卡采购业务http工具类:";
	private static final Logger LOG = Logger.getLogger(HttpUtil.class);
	private static final Gson gson = new Gson();
	private static final HttpClient httpClient = new HttpClient ( );
	
	public static enum CHARSET {
        GBK("gbk"), UTF_8("utf-8"), ISO_8859_1("iso-8859-1");
        private String charset;

        public String getCharset ( ) {
            return charset;
        }

        public void setCharset ( String charset ) {
            this.charset = charset;
        }

        CHARSET(String charset) {
            this.charset = charset;
        }
    }
	
	public static void main(String[] args) throws Exception{
		String url = "http://121.43.178.122:8081/d/hs/pf/commoncCoupon/api";
		Map<String, String> headers = new HashMap<>();
		headers.put("characterSet", "00");
		headers.put("strVendorCode", "tw8at51qz3cmzoz0i3");
		headers.put("signType", "MD5");
		
		headers.put("verifyCode", "12312312");//Body进行AES加密后，再进行MD5加密 ，加密字符串为商户秘钥
		headers.put("strActionType", "pfgenCouponList");
		headers.put("timestamp", "2017-12-07 15:15:00.123");//yyyy-MM-dd hh:m:ss.SSS
		
		Map<String, String> params = new HashMap<>();
		params.put("couponType", "IiQ8TFv8Vr8f");//电子券类型请求编码,每一个电子券类型的唯一标识
		params.put("batchNo", "12345");//最大长度12
		params.put("maxResult", "1");//最大长度6
		params.put("random", "123456");//6位随机数
		
		String data = gson.toJson(params);
		data = "A3WCFgRVt0baw7mgTKZdtPjYpRhKI2QYIZD45SyEDJKK3aKrJLWCurjraUswSBYnuEp+wjjskyaouUX5nrLTJogpdrBx5VOf1kqkKzFUk=";
		String res = HttpUtil.post(url, params, headers,data);
		JSONObject ticketJson = JSONObject.fromObject(res);
	}
	
	public static final String post(String url, Map<String, String> params, Map<String, String> headers,String data) {
		LOG.info(LOGPRE + "post params=" + gson.toJson(params) + ",headers=" + gson.toJson(headers));
		trustAllHosts();
		PostMethod postMethod = initialWithHeader(url, headers);
		if(params == null || params.isEmpty()){
			LOG.error(LOGPRE + "请求参数为空");
			return null;
		}
		
//		List<NameValuePair> list = new ArrayList<>();
//		for (Entry<String, String> entry : params.entrySet()) {
//			list.add(new NameValuePair(entry.getKey(), entry.getValue()));
//		}
//		postMethod.setRequestBody(list.toArray(new NameValuePair[0]));
		
		try {
			RequestEntity entity = new StringRequestEntity(data, "application/json","UTF-8");
	        postMethod.setRequestEntity(entity);
	        
			httpClient.executeMethod(postMethod);
			String response = new String(postMethod.getResponseBody(), parseCharset(headers.get("Content-Type")));
			LOG.info(LOGPRE + "post response=" + gson.toJson(response));
			return response;
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
		}
		return null;
	}
	
	private static String parseCharset ( String contentType ) {
        int index = 0;
        if (StringUtils.isNotBlank ( contentType ) && ( index = contentType.indexOf ( "charset" ) ) != -1) {
            return contentType.substring ( index + 8 );
        }
        return CHARSET.UTF_8.getCharset ( );
    }
	
	private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager ( ) {
        public X509Certificate[] getAcceptedIssuers ( ) {
            return new X509Certificate[] {};
        }

        public void checkClientTrusted ( X509Certificate[] chain , String authType )
            throws CertificateException {
        }

        public void checkServerTrusted ( X509Certificate[] chain , String authType )
            throws CertificateException {
        }
    } };
	
	private static void trustAllHosts ( ) {
        try {
            SSLContext sc = SSLContext.getInstance ( "TLS" );
            sc.init ( null , trustAllCerts , new SecureRandom ( ) );
            HttpsURLConnection.setDefaultSSLSocketFactory ( sc.getSocketFactory ( ) );
        } catch (Exception e) {
        	LOG.error ( e.getMessage ( ) , e );
        }
    }

	private static PostMethod initialWithHeader ( String url , Map<String, String> headers ) {
        PostMethod postMethod = new PostMethod ( url );
        for (Entry<String, String> entry : headers.entrySet ( )) {
            postMethod.addRequestHeader ( entry.getKey ( ) , entry.getValue ( ) );
        }
        return postMethod;
    }
}
